<template>
  <section class="page">
    <headerbar>通知消息{{ count > 0 ? "(" + count + ")" : "" }} </headerbar>

    <div id="receive" class="mui-active">
      <div class="d-scroll list-text" style="">
        <cube-scroll ref="scroll" :options="options" @pulling-up="onPullingUp" @pulling-down="onPullingDown"
                     :scrollEvents="['scroll-end']"
                     v-remainScrollCube="'noticeNew'"
        >
          <fetchData
            v-if="isLoading"
            :loading="isLoading"
            :data="swipeData"
          ></fetchData>
          <abnormal @refresh="receive" v-if="abnormal"></abnormal>
          <cube-swipe :key="newmemorabilias">
            <transition-group name="swipe" tag="div">
              <div
                class=""
                v-for="(item, index) in swipeData"
                :key="item.msgId"
              >
                <cube-swipe-item
                  ref="swipeItem"
                  :btns="item.btns"
                  :index="index"
                  @btn-click="action"
                >
                  <div @click="goDetail(item,index)" class="tongzhi-item">
                    <div class="icon" :style="getMyColor(item)">
                      {{ getWritten(item) }}
                    </div>
                    <div class="cont">
                      <h1>
                        {{ getType(item) }}
                        <span class="topSpan">查看详情 >></span>
                      </h1>
                      <div class="color-tip">标题：{{ item.msgTitle }}</div>
                      <div class="color-tip">
                        状态：<span :class="fontColor(item)">{{
                          isRead(item)
                        }}</span>
                      </div>
                      <div class="color-tip">
                        发送时间：{{ getTime(item.createTime) }}
                      </div>
                      <div class="color-tip"></div>
                      <!--                      <div class="look-more">查看详情 <i class="icon-arrow"><img src="../../../../static/images/dangjian/dangwu/arrow-left.png" alt=""></i></div>-->
                    </div>
                  </div>
                </cube-swipe-item>
              </div>
            </transition-group>
          </cube-swipe>
          <!-- <div
            class="text-center no-data"
            v-if="!abnormal && !isLoading && swipeData.length === 0"
          >
            <img src="../../../../static/images/no_data.png" alt="" />
            <p>暂无数据</p>
          </div>
          <onBottom v-else-if="onBottom"></onBottom> -->
          <!-- W noData -->
          <noData
            v-if="!abnormal && !isLoading && swipeData.length === 0"
          ></noData>
          <onBottom v-else-if="onBottom"></onBottom>
        </cube-scroll>
      </div>
    </div>
  </section>
</template>

<script>
import tools from "@/utils/tools";
import api from "@/common/config/api";
import loginService from "@/service/loginService";
import moment from "moment";
export default {
  name: "noticeNew",
  data() {
    return {
      count: 0,
      countNum: true,
      abnormal: false,
      isLoading: true,
      getDict: [],
      fn: tools,
      pageIndex: 1,
      launchPageIndex: 1,
      tabIndex: 0,
      options: {
        pullUpLoad: true,
        pullDownRefresh: {
          threshold: 90,
          stop: 0,
          txt: ' '
        },
        scrollbar: false,
      },
      onBottom: false, // W onBottom
      launchOptions: {
        pullUpLoad: true,
        scrollbar: false,
      },
      swipeData: [],
      sendSwipeData: [],
      permission: "-1",
      dataList: [],
      userInfo: this.$store.state.userInfo,
      newmemorabilias: "",
    };
  },
  created() {
    this.$route.meta.keepAlive = true
    this.init()
  },
  beforeRouteLeave(to, from, next) {
    this.$route.meta.keepAlive = to.name === 'noticeNewDetail'
    if(this.$route.meta.keepAlive) {
      this.$store.commit('addRoute','noticeNew')
    }else {
      this.$store.commit('removeRoute','noticeNew')
      this.$destroy()
    }
    next()
  },
  methods: {
    init() {
      this.receiveData();
      this.getDictValue();
      this.count = this.$store.state.count;
    },
    receive() {
      this.swipeData = [];
      this.tabIndex = 0;
      this.pageIndex = 1;
      this.receiveData();
    },
    send() {
      this.sendSwipeData = [];
      this.tabIndex = 1;
      this.launchPageIndex = 1;
      this.sendData();
    },
    receiveData() {
      this.onBottom = false;
      this.abnormal = false;
      this.isLoading = true;
      let data = {
        loginId: "20160503155632000078",
        recUserId: this.userInfo.id,
        limit: 10,
        page: this.pageIndex + "",
        // pageNo: this.pageIndex + '',
        pageSize: "20",
      };
      // this.fetchService.pageMsg(data).then(res => {
      //
      //   this.dataList =res.data
      //   this.dataList.forEach((v, i) => {
      //     v.btns = []
      //     v.btns.push({
      //       action: 'deleteItem',
      //       text: '删除',
      //       color: '#ec5563'
      //     })
      //   })
      // })
      if (this.countNum) {
        this.fetchService.pageMsg(data).then((res) => {
          this.isLoading = false;
          if (res.code == 444) {
            this.swipeData = [];
            this.abnormal = true;
            return;
          }
          if (res.code === 0 && res.data.length < 1) {
            this.countNum = false; // 将上拉刷新禁用
            this.onBottom = true;
            this.$refs.scroll && this.$refs.scroll.forceUpdate && this.$refs.scroll.forceUpdate();
            return;
          }
          this.pageIndex++;
          this.swipeData = this.swipeData.concat(res.data || []);
          this.swipeData.forEach((v, i) => {
            v.btns = [];
            v.btns.push({
              action: "deleteItem",
              text: "删除",
              color: "#ec5563",
            });
          });
          setTimeout(() => {
            this.$refs.scroll && this.$refs.scroll.forceUpdate &&
              this.$refs.scroll.forceUpdate(true, false);
          }, 100);
        });
      } else {
        this.isLoading = false;
        this.onBottom = true;
        this.options.pullUpLoad = false;
      }
    },
    sendData() {
      this.tabIndex = 1;
      let data = {
        loginId: "3750",
        pageNo: this.launchPageIndex + "",
        pageSize: "20",
      };
      this.fetchService.mySendList(data).then((res) => {
        if (res.code === 200 && res.data.length < 1) {
          this.$refs.scroll && this.$refs.scroll.forceUpdate && this.$refs.scroll.forceUpdate();
          return;
        }
        this.launchPageIndex++;
        this.sendSwipeData = this.sendSwipeData.concat(res.data || []);
        setTimeout(() => {
          this.$refs.scroll.forceUpdate &&
            this.$refs.scroll.forceUpdate(true, false);
          this.launchOptions.pullUpLoad = false;
        }, 100);
      });
    },
    onPullingUp() {
      this.receiveData();
    },
    onPullingDown() {
      this.options.pullUpLoad = true
      this.onBottom = false
      this.countNum = true;
      this.swipeData = []
      console.log('onPullingDown')
      this.pageIndex = 1
      this.receiveData()
    },
    launchOnPullingUp() {
      this.sendData();
    },
    goDetail(data,index) {
      let params = {
        msgId: data.businessId,
      };
      let params1 = {
        isRead: "1",
        recId: data.recId,
      };
      // this.$store.state.count = 100
      if (data.isRead == 0) {
        this.$store.state.showFeedback = true
        if (data.category.indexOf("PARTY") != -1) {
          this.fetchService.optNodeMsgRead(params).then((res) => {
            if (res.code !== 0) {
              return;
            }
          });
        }
        this.fetchService.updateBox(params1).then((res) => {
          if (res.code !== 0) {
            return;
          }
        });
        this.swipeData[index].isRead = '1' //将消息置为已读
        this.$store.commit("updateCount", --this.count);
      }else if (data.isRead === '1') {
        this.$store.state.showFeedback = false
      }
      if (data.category.indexOf("PARTY") != -1) {
        this.$router.push({
          path: `/noticeNoticeDetail/${data.businessId}/0`,
        });
        return
      }
      // data.category=this.getType(data)
      this.$store.state.noticeNewDetail = data;
      this.$router.push({ path: `/noticeNewDetail` });
      // let content = JSON.parse(data.content)
      // let moduleKey = content.category
      // if (moduleKey === 'PARTY_NODE_ZZSH') { // 党支部会议通知
      //   let custom = content.custom
      //   let sourceId = custom.sourceId
      //   this.optResult(sourceId)
      //   this.setRead(data.id)
      // } else {
      //   this.$store.state.noticeNewDetail = data
      //   this.$router.push({path: `/noticeNewDetail`})
      // }
    },
    getTime(createTime) {
      return moment(createTime).format("YYYY年MM月DD日 HH:mm:ss");
    },
    getDictValue() {
      let data = {
        catKey: "GBZX",
        treeKey: "XSXG",
      };
      this.fetchService.dictValue(data).then((res) => {
        if (res.code === 0) {
          this.getDict = res.data;
        }
      });
    },
    isRead(data) {
      if (data.isRead === "0") {
        return "未读";
      } else {
        return "已读";
      }
    },
    getType(data) {
      let name = "通知消息";
      this.getDict.forEach((item) => {
        if (item.key == data.category) {
          name = item.name;
          return;
        }
      });
      return name;
    },
    getWritten(data) {
      // 获取文字
      let name = "通知";
      this.getDict.forEach((item) => {
        if (item.key == data.category) {
          name = item.descp.split("_")[1];
          return;
        }
      });
      return name;
    },
    getMyColor(data) {
      // 获取颜色
      let myColor = {
        //默认颜色
        background: "#2CAAFD",
      };
      this.getDict.forEach((item) => {
        if (item.key == data.category) {
          myColor.background = "#" + item.descp.split("_")[0];
          return;
        }
      });
      return myColor;
    },
    fontColor(status) {
      let colorName = {
        0: "color-red",
        1: "color-green",
      };
      return colorName[status.isRead];
    },
    optNodeMsgRead(msgId) {
      let data = {
        msgId: msgId,
      };
      this.fetchService.optNodeMsgRead(data).then((res) => {});
    },
    nodeMsgPrem() {
      let data = {};
      this.fetchService.nodeMsgPrem(data).then((res) => {
        if (res.code === 200) {
          this.permission = res.data.powerFlag;
        }
      });
    },
    goAddNotice() {
      if (this.permission === "2") {
        this.$router.push({ path: `/noticeNoticeAdd/2` });
        return;
      }
      let _this = this;
      this.$createDialog({
        type: "confirm",
        title: "选择通知类型",
        content: "",
        confirmBtn: {
          text: "组织通知",
          active: true,
          disabled: false,
          href: "javascript:;",
        },
        cancelBtn: {
          text: "党员通知",
          active: false,
          disabled: false,
          href: "javascript:;",
        },
        onConfirm: () => {
          this.$store.state.flagType = true;
          this.$router.push({ path: `/noticeNoticeAdd/1` });
        },
        onCancel: () => {
          this.$store.state.flagType = true;
          this.$router.push({ path: `/noticeNoticeAdd/2` });
        },
      }).show();
    },
    getNoticeList() {
      // this.isLoading = true
      let data = {
        businessId: "",
        category: "",
        content: "",
        createTime: "",
        delFlag: "",
        fullname: "",
        isRead: "",
        limit: 10,
        linkMsg: "",
        page: 0,
        recId: "",
        recUserId: "",
        sender: "",
        senderId: "",
        tenantId: "",
      };
      // if (window.android && window.android.getNoticeList) {
      //   let data = window.android.getNoticeList(this.userInfo.id)
      //   // this.isLoading = false
      //   this.dataList = JSON.parse(data)
      //   this.dataList.forEach((v, i) => {
      //     v.btns = []
      //     v.btns.push({
      //       action: 'deleteItem',
      //       text: '删除',
      //       color: '#ec5563'
      //     })
      //   })
      //   console.log('000000000', this.dataList)
      // }
    },
    deleteItem(item, index) {
      this.alertDialog(item, index);
    },
    action(btn, index) {
      let item = this.swipeData[index];
      this[btn.action](item, index);
    },
    // getTitle (data) {
    //   let content = JSON.parse(data.content)
    //   return content.title
    // },
    // getTimes (data) {
    //   let content = JSON.parse(data.content)
    //   return this.getTime(content.sendTime)
    // },
    // setRead (id) {
    //   if (window.android && window.android.updateRead) {
    //     window.android.updateRead(id)
    //   }
    // },
    optResult(sourceId) {
      let data = {
        msgId: sourceId,
      };
      this.fetchService.optResult(data).then((res) => {
        if (res.code === 200) {
          let tabIndex = 0;
          if (data.feedType === "0") {
            this.$store.state.showFeedback = true;
            this.optNodeMsgRead(data.msgId);
          } else {
            this.$store.state.showFeedback = false;
          }
          this.$router.push({
            path: `/noticeNoticeDetail/${sourceId}/${tabIndex}`,
          });
        }
      });
    },
    alertDialog(item, index) {
      let _this = this;
      this.$createDialog({
        type: "confirm",
        icon: "",
        title: "温馨提示",
        content: "确定删除吗？",
        confirmBtn: {
          text: "确定",
          active: true,
          disabled: false,
          href: "javascript:;",
        },
        cancelBtn: {
          text: "取消",
          active: false,
          disabled: false,
          href: "javascript:;",
        },
        onConfirm: () => {
          // if (window.android && window.android.newsDelete) {
          //   let result = window.android.newsDelete(item.id)
          //   if (result === '0') {
          //     _this.dataList.splice(index, 1)
          //     _this.tools.tip('删除成功')
          //     _this.newmemorabilias = Date.now()
          //   } else {
          //     _this.tools.tip('删除失败')
          //   }
          // }
          this.fetchService.innerMsg(item.recId).then((res) => {
            if (res.code === 0) {
              let params ={ //用于删除接受消息的人员
                msgId: item.businessId,
                userId: this.userInfo.id
              }
              this.fetchService.delMsgMyReceive(params).then((res) => {})//调党务的删除
              this.$store.commit("updateCount", --this.count);
              _this.tools.tip("删除成功");
              _this.swipeData.splice(index, 1);
              _this.newmemorabilias = Date.now();
            } else {
              _this.tools.tip("删除失败");
            }
          });
        },
        onCancel: () => {},
      }).show();
    },
    /*判断是否存在某个值*/
    isHasFocus(userId, list) {
      let ret = false;
      list.some((v) => {
        if (v.recId === userId) {
          ret = true;
          return false;
        }
      });
      return ret;
    },
  },
};
</script>

<style scoped>
</style>
